package com.todod.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.todod.common.util.MinIoUtils;
import com.todod.common.util.SnowflakeIdGenerator;
import com.todod.dto.BaseFileDto;
import com.todod.dto.FileDto;
import com.todod.exception.UploadFileException;
import com.todod.mapper.BaseFileMapper;
import com.todod.model.BaseFile;
import com.todod.service.IBaseFileService;

/**
 * <p>
 * 附件表 服务实现类
 * </p>
 *
 * @author gmm
 * @since 2021-08-09
 */
@Service
@Transactional
public class BaseFileServiceImpl extends ServiceImpl<BaseFileMapper, BaseFile> implements IBaseFileService {

	@Value("${file.visit}")
	private String visi;
	@Value("${file.upload.path}")
	private String uploadPath; // 文件路径
	@Value("${file.upload.mapping}")
	private String showPath; // 映射路径
	// 存储桶名称
	@Value("${minio.bucketName}")
	private String bucketName;
	@Autowired
	private MinIoUtils minIoUtils;

	@Override
	public Map<String, Object> saveUploadFile(Long userId, HttpServletRequest request, String linkId, String fileType) {
		try {
//			String newDate = TododDate.getInstance().getSimpledate();
//
//			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
//			MultipartFile uploadFile = req.getFile("uploadfile_ant");
//
//			// 上传路径
//			String root = uploadPath;
//
//			String abstractPath = root + "upload" + File.separator + newDate;
//
//			String rPath = showPath + "upload" + "/" + newDate;
//
//			File dir = new File(abstractPath);
//			if (!dir.exists()) {
//				dir.mkdirs();
//			}
//
//			String originalName = uploadFile.getOriginalFilename();
//			String suffix = StringUtils.substringAfterLast(originalName, ".");
//
//			String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
//			// 保存数据
//			FileCopyUtils.copy(uploadFile.getInputStream(),
//					new FileOutputStream(abstractPath + File.separator + fileName));
//
//			String relativePath = rPath + "/" + fileName;

			String abstractPath = null, relativePath = null;

			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
			MultipartFile uploadFile = req.getFile("uploadfile_ant");// 返回上传文件的内容和描述
			String originalName = uploadFile.getOriginalFilename();
			String file_ext_name = originalName.substring(originalName.lastIndexOf(".") + 1);

			relativePath = minIoUtils.upload(uploadFile, bucketName, null);
			abstractPath = visi + relativePath;

			Long fileId = saveData(userId, originalName, relativePath, file_ext_name, uploadFile.getSize(),
					abstractPath, relativePath, linkId, fileType);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("path", visi + relativePath);
			map.put("fileId", fileId);
			return map;
		} catch (Exception e) {
			log.error("file_upload", e);
			throw new UploadFileException("上传文件失败");
		}
	}

	@Override
	public void deleteData(Long id) {
		this.removeById(id);
	}

	@Override
	public List<FileDto> getByLinkId(String id, String type) {
		return baseMapper.getByLinkId(id, type);
	}

	private Long saveData(Long userId, String originalName, String fileName, String suffix, long size,
			String abstractPath, String relativePath, String linkId, String fileType) {
		List<BaseFile> list = baseMapper.selectByLinkId(linkId, fileType);

		if (list.size() > 0) {
			QueryWrapper<BaseFile> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("bf_link_id", linkId);
			queryWrapper.eq("bf_file_type", fileType);

			BaseFile baseFile = baseMapper.selectOne(queryWrapper);
			baseFile.setOriginalName(originalName);
			baseFile.setFileSize(size);
			baseFile.setFileName(fileName);
			baseFile.setFileType(fileType);
			baseFile.setSuffix(suffix);
			baseFile.setAbstractPath(abstractPath);
			baseFile.setRelativePath(relativePath);
			baseFile.setLinkId(Long.valueOf(linkId));
			baseFile.setSortNum(1);

			baseFile.setModifyuserId(userId);
			baseFile.setModifytimeTi(LocalDateTime.now());
			baseMapper.updateById(baseFile);

			return baseFile.getId();
		} else {
			BaseFile baseFile = new BaseFile();

			baseFile.setId(SnowflakeIdGenerator.getId());
			baseFile.setOriginalName(originalName);
			baseFile.setFileSize(size);
			baseFile.setFileName(fileName);
			baseFile.setFileType(fileType);
			baseFile.setSuffix(suffix);
			baseFile.setAbstractPath(abstractPath);
			baseFile.setRelativePath(relativePath);
			baseFile.setLinkId(Long.valueOf(linkId));
			baseFile.setSortNum(1);

			baseFile.setCreateuserId(userId);
			baseFile.setCreatetimeTi(LocalDateTime.now());
			baseMapper.insert(baseFile);

			return baseFile.getId();
		}
	}

	@Override
	public List<BaseFileDto> getFileList(String linkId, String filetype) {
		List<BaseFileDto> list = baseMapper.selectByLinkIdAndFileType(linkId, filetype);

		for (BaseFileDto baseFileDto : list) {
			baseFileDto.setUrl(visi + baseFileDto.getRelativePath());
		}

		return list;
	}

	@Override
	public String saveUploadFile1(Long _userId, HttpServletRequest request, String linkId, String filetype) {
		try {
//			String newDate = TododDate.getInstance().getSimpledate();
//
//			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
//			MultipartFile uploadFile = req.getFile("uploadfile_ant");
//
//			// 上传路径
//			String root = uploadPath;
//
//			String abstractPath = root + "upload" + File.separator + newDate;
//
//			String rPath = showPath + "upload" + "/" + newDate;
//
//			File dir = new File(abstractPath);
//			if (!dir.exists()) {
//				dir.mkdirs();
//			}
//
//			String originalName = uploadFile.getOriginalFilename();
//			String suffix = StringUtils.substringAfterLast(originalName, ".");
//
//			String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
//			// 保存数据
//			FileCopyUtils.copy(uploadFile.getInputStream(),
//					new FileOutputStream(abstractPath + File.separator + fileName));
//
//			String relativePath = rPath + "/" + fileName;

			String abstractPath = null, relativePath = null;

			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
			MultipartFile uploadFile = req.getFile("uploadfile_ant");// 返回上传文件的内容和描述
			String originalName = uploadFile.getOriginalFilename();
			String file_ext_name = originalName.substring(originalName.lastIndexOf(".") + 1);

			relativePath = minIoUtils.upload(uploadFile, bucketName, null);
			abstractPath = visi + relativePath;

			saveData1(_userId, originalName, relativePath, file_ext_name, uploadFile.getSize(), abstractPath,
					relativePath, linkId, filetype);

			return visi + relativePath;
		} catch (Exception e) {
			log.error("file_upload", e);
			throw new UploadFileException("上传文件失败");
		}
	}

	private void saveData1(Long userId, String originalName, String fileName, String suffix, long size,
			String abstractPath, String relativePath, String linkId, String fileType) {
		// List<BaseFile> list = baseMapper.selectByLinkId(linkId, fileType);
		BaseFile baseFile = new BaseFile();
		baseFile.setId(SnowflakeIdGenerator.getId());
		baseFile.setOriginalName(originalName);
		baseFile.setFileSize(size);
		baseFile.setFileName(fileName);
		baseFile.setFileType(fileType);
		baseFile.setSuffix(suffix);
		baseFile.setAbstractPath(abstractPath);
		baseFile.setRelativePath(relativePath);
		baseFile.setLinkId(Long.valueOf(linkId));
		baseFile.setSortNum(1);
		baseFile.setCreateuserId(userId);
		baseFile.setCreatetimeTi(LocalDateTime.now());
		baseMapper.insert(baseFile);
	}
}
